package com.hzw.saas.web.admin.hpc.controller;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.hzw.saas.api.hpc.IHpcAccountUserService;
import com.hzw.saas.api.hpc.query.SubHpcAccountQuery;
import com.hzw.saas.api.property.IPropertyService;
import com.hzw.saas.api.property.enmus.SysDictKeyEnum;
import com.hzw.saas.api.user.bo.CustomerBO;
import com.hzw.saas.common.config.annotation.SysLog;
import com.hzw.saas.common.config.util.PageParam;
import com.hzw.saas.common.config.util.PageUtils;
import com.hzw.saas.web.admin.hpc.dto.CustomerShareDto;
import com.hzw.saas.web.admin.hpc.param.AllotSubHpcAccountParam;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiOperationSort;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @author sonam
 * @sine 2021/11/26 1:07 下午
 */
@Slf4j
@Api(tags = "HPC/HPC账号分享")
@RestController
@RequiredArgsConstructor
@RequestMapping("/hpc/account")
public class HpcShareController {

    private final IHpcAccountUserService hpcAccountUserService;

    @Resource(name = IPropertyService.SYS_DICT_BEAN)
    private IPropertyService<SysDictKeyEnum> propertyService;

    @PostMapping("/allot")
    @ApiOperation(value = "分配HPC共享账号", notes = "指定用户ID，共享HPC帐号")
    @ApiOperationSort(1)
    @SysLog(operation = "分配HPC共享账号", mode = 3)
    public ResponseEntity<Void> allotHpcAccountToUser(@Validated @RequestBody AllotSubHpcAccountParam hpcAccountParam) {
        // 获取默认的过期时间
        String propertyValue = propertyService.getPropertyValue(SysDictKeyEnum.SHARE_HPC_EXPIRE_TIME, "6");
        int offsetDay;
        try {
            offsetDay = Integer.parseInt(propertyValue);
        } catch (Exception e) {
            offsetDay = 6;
        }

        List<SubHpcAccountQuery> hpcAccountQueries = new ArrayList<>();
        int finalOffsetDay = offsetDay;
        hpcAccountParam.getUserIds().forEach(userId -> {
            SubHpcAccountQuery hpcAccountQuery = new SubHpcAccountQuery();
            hpcAccountQuery.setHpcAccountUserId(hpcAccountParam.getHpcAccountUserId());
            hpcAccountQuery.setUserId(userId);
            hpcAccountQuery.setSubHpcAccountStatus(hpcAccountParam.getStatus());

            if (Objects.isNull(hpcAccountParam.getExpireTime())) {
                DateTime expireTime = DateUtil.offset(DateUtil.date(), DateField.MONTH, finalOffsetDay);
                hpcAccountQuery.setExpireTime(expireTime);
            } else {
                hpcAccountQuery.setExpireTime(hpcAccountParam.getExpireTime());
            }
            hpcAccountQueries.add(hpcAccountQuery);
        });

        hpcAccountUserService.addSubAccountUser(hpcAccountQueries);
        return ResponseEntity.ok().build();
    }

    @PostMapping("/cancel/share/{hpcAccountUserId}/{userId}")
    @ApiOperation(value = "解绑用户的共享HPC账号", notes = "解绑用户的共享HPC账号")
    @ApiOperationSort(2)
    @SysLog(operation = "解绑用户的共享HPC账号", mode = 3)
    public ResponseEntity<Void> cancelShareHpcAccount(@ApiParam(value = "HPC用户ID") @PathVariable String hpcAccountUserId,
                                                      @ApiParam(value = "平台用户ID") @PathVariable String userId) {
        hpcAccountUserService.cancelShareHpcAccount(hpcAccountUserId, userId);
        return ResponseEntity.ok().build();
    }


    @GetMapping("/{userId}/{hpcAccountUserId}/need/share/list")
    @ApiOperation(value = "搜索需要共享的客户列表", notes = "指定用户ID，搜索需要共享的客户列表")
    @SysLog(operation = "搜索需要共享的客户列表")
    @ApiOperationSort(3)
    public ResponseEntity<IPage<CustomerShareDto>> searchNeedShareList(PageParam pageParam,
                                                                       @ApiParam(value = "平台用户ID") @PathVariable String userId,
                                                                       @ApiParam(value = "HPC用户ID") @PathVariable String hpcAccountUserId,
                                                                       @ApiParam(value = "模糊查询字段(客户姓名,客户邮箱,客户手机号码)") @RequestParam(defaultValue = "", required = false) String fuzzy) {
        IPage<CustomerBO> customerBOIPage = hpcAccountUserService.listNeedShareCustomerByUserId(pageParam, userId, hpcAccountUserId, fuzzy, null);
        return ResponseEntity.ok(PageUtils.convert(customerBOIPage, CustomerShareDto.class));
    }

    @GetMapping("/{userId}/{hpcAccountUserId}/share/list")
    @ApiOperation(value = "搜索已共享的客户列表", notes = "指定用户ID，搜索已共享的客户列表")
    @SysLog(operation = "搜索已共享的客户列表")
    @ApiOperationSort(4)
    public ResponseEntity<IPage<CustomerShareDto>> searchShareList(PageParam pageParam,
                                                                   @ApiParam(value = "平台用户ID") @PathVariable String userId,
                                                                   @ApiParam(value = "HPC用户ID") @PathVariable String hpcAccountUserId,
                                                                   @ApiParam(value = "模糊查询字段(客户姓名,客户邮箱,客户手机号码)") @RequestParam(defaultValue = "", required = false) String fuzzy) {
        IPage<CustomerBO> customerBOIPage = hpcAccountUserService.listShareCustomerByUserId(pageParam, userId, hpcAccountUserId, fuzzy, null);
        return ResponseEntity.ok(PageUtils.convert(customerBOIPage, CustomerShareDto.class));
    }
}
